/**
 * Created by Administrator on 2018/8/28.
 */
var triArray = new Array();
var insideGrid;
var startGrid;
var $$scope;
var codeNow = "";
var tempOriginSelect;
var $backlogPersonList;
var $CertusJsonAjax;

function surplusMet(triArray, triCode, nowValue, CertusJsonAjax, scope) {
    $CertusJsonAjax = CertusJsonAjax;
    for (var sb in triArray) {
        if (triArray[sb].triCode == triCode) {

            var additional = 0;
            for(var ff in triArray[sb].projectPercent){
                if(triArray[sb].projectPercent[ff].projId == scope.triPercent.projId){
                    additional = triArray[sb].projectPercent[ff].money;
                }
            }
            //过滤 数据
            param = {
                total: triArray[sb].money,
                now: nowValue,
                datas: triArray[sb].projectPercent,
                additional:additional
            }
            CertusJsonAjax.ajaxNode("calculate", "surplus", param, function (res) {

                triArray[sb].originSurplus = res.surplus;
                scope.surplus = res.surplus;
                scope.$apply();
            })
        }
    }
}


function addCCbxLc($scope, $route, CertusFormAjax, CertusJsonAjax, $location, $http, $cookies, $routeParams, backlogPersonList) {
    $scope.trEntity = {};
    $backlogPersonList = backlogPersonList
    triArray = new Array();
    $$scope = $scope;
    $scope.trEntity = {
        trCode: "tr-" + new Date().getTime() + Math.floor(Math.random() * 10000),
        items: triArray
    };

    $scope.triPercentDis = true;

    /////////////初始化 草稿 记录
    CertusFormAjax.ajax("listDraftCCBX", {
        expenseType: 'trmType'
    }, function (res) {
        if (res.data) {
            $scope.dafts = res.data;
        }
    })

    var nowTriburse;

    function isSaveRetribursementName(element) {
        return element.comName.indexOf(nowTriburse) > -1;
    }

    //客户 公司 code
    $scope.$watch("trEntity.borrowCode", function (newValue, old, scope) {
        if (old && newValue) {
            if (newValue.indexOf(old) > -1) {
                nowTriburse = newValue;
                scope.triburseSelect = scope.triburseSelect.filter(isSaveRetribursementName);
                if (scope.triburseSelect.length) {
                    if (scope.triburseSelect.length == 1) {
                        // scope.receptionTribursementEntity.borrowCode = scope.dataList.cusCompSelect[0].id;
                        scope.trEntity.borrowCode = scope.triburseSelect[0].comName;
                    }
                }
                return;
            }
        }
        //直接去数据库 查询
        CertusFormAjax.ajax("borrowingEntityList", {borrowCode: newValue}, function (res) {
            scope.triburseSelect = res.data;
            if (scope.triburseSelect.length) {
                if (scope.triburseSelect.length == 1) {
                    // scope.receptionTribursementEntity.customUnitId = scope.dataList.cusCompSelect[0].id;
                    scope.trEntity.borrowCode = scope.triburseSelect[0].comName;
                }
            }
        })
    })
    //打开 草稿记录
    $scope.openDraf = function (a) {
        CertusFormAjax.ajax("openDraf", {
            trCode: a
        }, function (res) {
            if (res.data) {
                $$scope.trEntity = res.data;
                if ($$scope.trEntity.travelCode && $$scope.trEntity.travelCode != "") {
                    $scope.travelCodeChange($$scope.trEntity.travelCode);
                }
                triArray = res.data.items;
                if (triArray) {
                    for (var b in triArray) {
                        if (triArray[b]) {
                            surplusMet(triArray, b, 0, CertusJsonAjax, $scope);
                        }
                    }
                }
                startGrid.exhibitDatas = res.data.items;
                startGrid.refresh(false);
                $("#yourModal").modal('hide');
            }
        })
    }

    //使用 草稿 方法 public

    //监听修改 项目名称
    $scope.$watch("triPercent.projName", function (newValue, old, scope) {
        if (old && newValue) {
            if (newValue.indexOf(old) > -1) {
                nowProjName = newValue;
                scope.userProjSelect2 = scope.userProjSelect2.filter(isSaveProjName);
                if (scope.userProjSelect2.length) {
                    if (scope.userProjSelect2.length == 1) {
                        scope.triPercent.projId = scope.userProjSelect2[0].projId;
                        scope.triPercent.projName = scope.userProjSelect2[0].projName;
                    }
                }
                if (!scope.userProjSelect2 || scope.userProjSelect2.length == 0) {
                    scope.triPercent.projId = "";
                    scope.triPercent.projName = "";
                }
                return;
            }
        }

        //直接去数据库 查询
        CertusFormAjax.ajax("relatedProj", {
            param: newValue
        }, function (res) {
            scope.userProjSelect2 = res.data;
            if (scope.userProjSelect2.length) {
                if (scope.userProjSelect2.length == 1) {
                    scope.triPercent.projId = scope.userProjSelect2[0].projId;
                    scope.triPercent.projName = scope.userProjSelect2[0].projName;
                }
            }
        })
    })


    var picker3 = $('#dateTime1').datetimepicker({
        format: 'YYYY-MM-DD',
        locale: moment.locale('zh-cn')
    }).on('dp.hide', function (e) {
        var result = new moment(e.date).format('YYYY-MM-DD');
        if (result && !angular.isUndefined(result)) {
            $scope.trItem.startDate = result;
            $scope.$apply();
        }
        ;
    })

    var picker4 = $('#dateTime2').datetimepicker({
        format: 'YYYY-MM-DD',
        locale: moment.locale('zh-cn')
    }).on('dp.hide', function (e) {
        var result = new moment(e.date).format('YYYY-MM-DD');
        if (result && !angular.isUndefined(result)) {
            $scope.trItem.endDate = result;
            $scope.$apply();
        }
    })

    //报销 条目
    $scope.ccClassSelect = [{
        name: "火车/汽车",
        code: "train"
    },
        {
            name: "飞机",
            code: "plan"
        },
        {
            name: "交通费用",
            code: "traffic"
        },
        {
            name: "住宿费用",
            code: "hotel"
        },
        // {
        //     name: "招待费",
        //     code: "repetition"
        // },
        {
            name: "其他费用",
            code: "others"
        },
        {
            name: "出差补助",
            code: "travelAllowance"
        }
    ]

    $scope.ccCompanySelect = [{
        name: "赛特斯上海",
        code: "STSSH"
    },
        {
            name: "赛特斯南京",
            code: "STSNJ"
        },
        {
            name: "赛特斯广州",
            code: "STSGD"
        },
        {
            name: "赛特斯北京",
            code: "STSBJ"
        },
    ]

    //选取 可以 直接 使用 的出差单号
    CertusFormAjax.ajax("availablePolicyNumber", {}, function (res) {
        if (res.data) {
            $scope.availablePolicyNumberSelect = res.data;
        }
    })
    //项目 金额 变化
    $$scope.$watch("triPercent.money", function (newValue, oldValue, scope) {

        if(newValue){
            surplusMet(triArray,codeNow,newValue,$CertusJsonAjax,$$scope);
        }else{
            surplusMet(triArray,codeNow,0,$CertusJsonAjax,$$scope);
        }
    });

    $scope.travelCodeChange = function (a) {
        if (a) {
            for (var j in triArray) {
                triArray[j].projectPercent = null;
            }
            //初始化可以选取的 项目编号
            CertusFormAjax.ajax("availableProjNumber", {
                travelCode: a
            }, function (res) {
                if (res.data) {

                    $scope.availableProjNumberSelect = res.data;
                    tempOriginSelect = res.data;
                }
            })
            $scope.triPercentDis = false;
            return;
        }
        $scope.triPercentDis = true;

    }

    $scope.addItem = function () {

        $scope.trItem = {};
        $("#dateTime1").val("");
        $("#dateTime2").val("");


        $(".afrinfo").show();
    }

    $scope.saveDraftCCBX = function () {
        $scope.trEntity.expenseType = 'trmType';
        if ($scope.trEntity.chargeAgainest || $scope.trEntity.borrowCode) {
            if ($$scope.trEntity.chargeAgainest && $$scope.trEntity.borrowCode) {

            } else {
                layer.msg("请补全冲销信息");
                return;
            }
        }
        CertusJsonAjax.ajax("saveDraftCCBX", $scope.trEntity, function (res) {
            if (res.data) {
                if (res.data == "success") {
                    window.history.back();
                }
            }
        })
    }

    $scope.startCCBXLc = function () {
        $scope.trEntity.expenseType = 'trmType';
        CertusJsonAjax.ajax("startCCBXLc", $scope.trEntity, function (res) {
            if (res.data) {
                if (res.data.succed == "success") {
                    nextApprovalManView(res.data.tip);
                    window.history.back();
                    return;
                }
                layer.msg(res.data.succed);
            }
        })
    }

    function isDifferentPercent(element) {
        return element.projId != projIdNow;
    }


    $scope.percentSubmit = function (a) {

        projIdNow = a;
        for (var ii in $$scope.availableProjNumberSelect) {
            if ($$scope.availableProjNumberSelect[ii].code == a) {
                $$scope.triPercent.projName = $$scope.availableProjNumberSelect[ii].name
            }
        }
        if (!$$scope.triPercent.projName) {
            layer.msg("请选择项目(或者项目已经分配完成)");
            return;
        }
        if (nowprojectPercent) {
            for (var i in nowprojectPercent) {
                if (nowprojectPercent[i].projId == a) {
                    nowprojectPercent[i] = $$scope.triPercent;
                }
            }

            nowprojectPercent = nowprojectPercent.filter(isDifferentPercent);
            nowprojectPercent.push($$scope.triPercent);
            for (var h in triArray) {
                if (triArray[h].triCode == codeNow) {
                    triArray[h].projectPercent = nowprojectPercent;
                    surplusMet(triArray, h, 0, CertusJsonAjax, $scope);
                }
            }
        }
        $(".haddpro").hide();
    }

    $scope.disDraft = function () {
        $("#yourModal").modal('show');
    }

    CertusFormAjax.ajax("belongCompanyName", {}, function (res) {
        var companyCode = res.data;
        if (companyCode == "STSJT") {
            $scope.belongCompanyName = "赛特斯集团";
        } else if (companyCode == "STSGD") {
            $scope.belongCompanyName = "赛特斯广东";
        } else if (companyCode == "HFKJ") {
            $scope.belongCompanyName = "浩方科技";
        } else if (companyCode == "HFXX") {
            $scope.belongCompanyName = "浩方信息";
        } else if (companyCode == "STSBJ") {
            $scope.belongCompanyName = "赛特斯北京";
        } else if (companyCode == "STSNJ") {
            $scope.belongCompanyName = "赛特斯南京";
        }
    });

    var userPinin;

    function isSamePinyin(element) {
        if (userPinin) {
            userPinin = userPinin.toUpperCase();
        }
        var pinyin = "";
        var userName2 = "";
        var userName = "";
        if (element.pinyin) {
            pinyin = element.pinyin.toUpperCase();
        }
        if (element.userName2) {
            userName2 = element.userName2.toUpperCase();
        }
        if (element.userName) {
            userName = element.userName.toUpperCase();
        }

        //部门名称 联动 查询
        return pinyin.indexOf(userPinin) > -1 || userName2.indexOf(userPinin) > -1 || userName.indexOf(userPinin) > -1;
    }

    $scope.$watch('trEntity.assignee', function (principalName, oldName, b) {
        if (principalName != "") {
            var userSelect = $scope.userSelect;
            if (principalName && principalName.indexOf(oldName) > -1 && b.userSelect && b.userSelect.length > 0) {
                userPinin = principalName;
                b.userSelect = b.userSelect.filter(isSamePinyin);
            } else {
                CertusFormAjax.ajax("relatedUser", {name: principalName}, function (res) {
                    if (res.data && res.data.length > 0) {
                        b.userSelect = res.data;
                    }
                });
            }

            if (b.userSelect && b.userSelect.length == 1) {
                var userSelect2 = userSelect[0];
                $$scope.trEntity.assignee = userSelect2.userName + "(" + userSelect2.userId + ")";
                $$scope.trEntity.assigneeId = userSelect2.userId;


                //重新 触发 下拉 数据 查询 方法
                CertusFormAjax.ajax("availablePolicyNumber", {"assigneeId": $$scope.trEntity.assigneeId}, function (res) {
                    if (res.data) {
                        $scope.availablePolicyNumberSelect = res.data;
                    }
                })
            }
        } else if (principalName == "" || !principalName) {
            $scope.trEntity.travelCode = null;
            //还原 出差单 下拉
            CertusFormAjax.ajax("availablePolicyNumber", {}, function (res) {
                if (res.data) {
                    $scope.availablePolicyNumberSelect = res.data;
                }
            })
        }
    });

    $scope.itemSubmit = function () {

        if (certusValidateNotnullPolyfill()) {
            var changeTr = {};

            //补足 name

            $scope.trItem.trCompanyName = $scope.belongCompanyName;


            for (var k in $scope.ccClassSelect) {
                if ($scope.ccClassSelect[k].code == $scope.trItem.triClassCode) {
                    $scope.trItem.triClassName = $scope.ccClassSelect[k].name;
                }
            }
            // if ($scope.trItem.projectPercent) {
            //     $scope.trItem.originSurplus = $scope.trItem.money;
            //     for (var i in $scope.trItem.projectPercent) {
            //         $scope.trItem.originSurplus -= $scope.trItem.projectPercent[i].money;
            //     }
            // }
            // ;
            // if ($scope.trItem.originSurplus < 0) {
            //     layer.msg("目前项目分配钱，已经超过现有的总和");
            //     return;
            // }
            $scope.trItem.trCode = $scope.trEntity.trCode;
            $scope.trItem.triCode = "tri-" + new Date().getTime() + Math.floor(Math.random() * 10000);
            codeNow = $scope.trItem.triCode;
            triArray = triArray.filter(isDifferent);
            triArray.push($scope.trItem);
            //算出总金额
            $scope.trEntity.totalAmount = 0;
            for (var b in triArray) {
                $scope.trEntity.totalAmount += to2fixed(triArray[b].money);
            }
            startGrid.exhibitDatas = triArray;
            $$scope.trEntity.items = triArray;
            startGrid.refresh(false);
            surplusMet(triArray,$scope.trItem.triCode,$scope.trItem.money,CertusJsonAjax,$scope);

            $(".afrinfo").hide();
        }
    }


    $scope.closeAddItem = function () {
        $(".afrinfo").hide();
    }

    startGrid = $.fn.dlshouwen.grid.init(afrOptionCCBX);
    startGrid.exhibitDatas = triArray;

    $$scope.triPercentChange = function (a) {
        if (a) {
            surplusMet(triArray,a,0,$CertusJsonAjax,$$scope);
            // $$scope.triPercent.surplus = number;
            return
        }
        $$scope.triPercent.surplus = $$scope.originSurplus
    }

    $scope.editPercent = function (projId) {

        for (var i in triArray) {
            if (triArray[i].triCode == codeNow) {
                for (var j in triArray[i].projectPercent) {
                    $$scope.triPercent = triArray[i].projectPercent[j];
                    $$scope.triPercent.projId = projId + "";
                    // triArray[i].projectPercent = triArray[i].projectPercent.filter(isDiffPercent);
                    surplusMet(triArray,codeNow,0,CertusJsonAjax,$scope);
                }

            }
        }
        $("#myModal").modal('hide');
        $(".haddpro").show();
    }

    $$scope.delPercent =
        function (projId) {
            // layer.confirm('确认删除此数据？', {
            //     btn: ['确认', '取消'] //按钮
            // }, function () {
            for (var j in triArray) {
                if (triArray[j].triCode == codeNow) {
                    for (var i in triArray[j].projectPercent) {
                        if (triArray[j].projectPercent[i].projId == projId) {
                            projIdNow == projId;
                            triArray[j].originSurplus += triArray[j].projectPercent[i].money;
                            triArray[j].projectPercent = triArray[j].projectPercent.filter(isDiffPercent);
                            $$scope.nowprojectPercents = triArray[j].projectPercent;
                            return;
                        }
                    }
                }
            }
            //     layer.msg('删除成功');
            // });

        }

}


// 报销费用明细
var afrColumns1 = [{
    id: 'trCompanyName',
    title: '报销主体公司',
    width: 150,
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'triClassName',
    title: '报销类目',
    width: 150,
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'money',
    title: '金额',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
    }
}, {
    id: 'startDate',
    title: '开始日期',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    hideType: 'lg|md|sm|xs',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var date = new Date(record.startDate);
        var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd");
        return content;
    }
}, {
    id: 'endDate',
    title: '结束日期',
    type: 'string',
    width: 150,
    columnClass: 'text-center',
    hideType: 'lg|md|sm|xs',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var date = new Date(record.endDate);
        var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd");
        return content;
    }
}, {
    id: 'startAddr',
    title: '开始地点',
    type: 'string',
    width: 150,
    columnClass: 'text-center',
    hideType: 'lg|md|sm|xs',
}, {
    id: 'endAddr',
    title: '结束地点',
    type: 'string',
    width: 150,
    columnClass: 'text-center',
    hideType: 'lg|md|sm|xs',
}, {
    id: 'triNum',
    title: '原始单据数量',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    hideType: 'lg|md|sm|xs',
}, {
    id: 'trInstruction',
    title: '费用报销明细说明',
    type: 'string',
    columnClass: 'text-left',
}, {
    id: 'operation',
    title: '操作',
    width: 280,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '<button class="btn btn-xs btn-success" onclick="addProCC(\'' + record.triCode + '\');"><i class="icon-plus"></i>  项目占比</button>';
        content += '  ';
        content += '<button class="btn btn-xs btn-primary" onclick="disMyModal(\'' + record.triCode + '\');"><i class="icon-eye-open"></i>  项目占比</button>';
        content += '  ';
        content += '<button class="btn btn-xs btn-info" onclick="editCC(\'' + record.triCode + '\');"><i class="fa fa-edit"></i>  编辑</button>';
        content += '  ';
        content += '<button class="btn btn-xs btn-danger" onclick="delTriItem(\'' + record.triCode + '\');"><i class="fa fa-trash-o"></i>  删除</button>';
        return content;
    }
}];

function delTriItem(triCode) {
    layer.confirm('确认删除此数据？', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        for (var i in triArray) {
            if (triArray[i].triCode == triCode) {
                triArray = triArray.filter(isDifferent);
                startGrid.exhibitDatas = triArray;
                startGrid.refresh(false);
                $$scope.trEntity.items = triArray;
            }
        }
        layer.msg('删除成功');
    });

}

function dateChange1() {
    $$scope.startDate = $("#dateTime1").val();
    $$scope.$apply();
}

function dateChange2() {
    $$scope.endDate = $("#dateTime1").val();
    $$scope.$apply();
}

function disMyModal(triCode) {

    for (var i in triArray) {
        if (triArray[i].triCode == triCode) {
            if (triArray[i].projectPercent) {
                codeNow = triCode;
                nowprojectPercent = triArray[i].projectPercent;
                $$scope.trItem = triArray[i];
                $$scope.nowprojectPercents = nowprojectPercent;
                // $(".haddpro").show();
            }
        }
    }
    $$scope.$apply();
    $("#myModal").modal('show');
}

function isDifferentSelect(element) {
    return element.code != projIdNow;
}

var nowprojectPercent;

function addProCC(triCode) {

    for (var i in triArray) {
        if (triArray[i].triCode == triCode) {
            codeNow = triCode;
            $$scope.triPercent = {};
            triArray[i].originSurplus = triArray[i].money;
            if (!triArray[i].projectPercent) {
                surplusMet(triArray,codeNow,0,$CertusJsonAjax,$$scope);
                $$scope.availableProjNumberSelect = tempOriginSelect;
                triArray[i].projectPercent = [];
            } else {
                var tempSelect = tempOriginSelect;
                for (var j in triArray[i].projectPercent) {
                    triArray[i].originSurplus -= triArray[i].projectPercent[j].money
                    projIdNow = triArray[i].projectPercent[j].projId;
                    if (tempOriginSelect) {
                        tempSelect = tempSelect.filter(isDifferentSelect);
                    }
                }
                $$scope.availableProjNumberSelect = tempSelect;
                surplusMet(triArray,triCode,0,$CertusJsonAjax,$$scope);
            }
            $$scope.triPercent.surplus = triArray[i].originSurplus;
            $$scope.$apply();
            nowprojectPercent = triArray[i].projectPercent;
            $(".haddpro").show();

            return;
        }
    }
}

function haddpro1() {
    $(".haddpro").hide();
}

function editCC(triCode) {
    for (var i in triArray) {
        if (triArray[i].triCode == triCode) {
            $$scope.trItem = triArray[i];
        }
    }
    $(".afrinfo").show();
    $$scope.$apply();
}

function isDifferent(element) {
    return element.triCode != codeNow;
}

var afrOptionCCBX = {
    lang: 'zh-cn',
    ajaxLoad: false,
    extraWidth: 20,
    // loadURL:'url',
    exportFileName: '报销费用明细',
    datas: [],
    columns: afrColumns1,
    gridContainer: 'afrContainerCCBX',
    toolbarContainer: 'afrToolBarContainerCCBX',
    tools: '',
    pageSize: 10,
    pageSizeLimit: [10, 15, 20]
};

var projIdNow;

function isDiffPercent(element) {
    return element.projId != projIdNow;
}